import { h } from '@knno/dom/jsx';
import { Cell, CellProps } from './cell';
import { DateMode, DatePicker } from '../../components/datePicker/datePicker';

export type TimeCellProps = CellProps<TimeCell, TimeCellProps, string> & {
	mode?: DateMode;
};

export class TimeCell extends Cell<TimeCell, TimeCellProps, string> {
	init() {
		const mode = this.attrs.mode ?? 'dd';
		const valueStr = DatePicker.trimDateString(this.getValue(), mode);
		const value = DatePicker.parseDate(this.getValue(), mode);
		this.setValue(valueStr);
		this.on('click', () => {
			DatePicker.show({
				refer: this,
				mode: mode,
				date: value ? [value] : [],
				range: false,
				focus: true,
			}).onSelect((value) => {
				let v: Date | null;
				if (value instanceof Array) {
					if (value.length === 0) {
						v = null;
					} else {
						v = value[0];
					}
				} else {
					v = value;
				}
				this.setValue(DatePicker.formatDate(v, mode));
			});
		});
	}

	protected update(): void {
		this.text(this.getValue() ?? '');
	}
}
